package com.example.project.projectspringcloud.service.impl.video;

import com.example.project.projectspringcloud.common.Constants;
import com.example.project.projectspringcloud.common.OperationException;
import com.example.project.projectspringcloud.dao.sys.SysConfigMapper;
import com.example.project.projectspringcloud.dao.user.UserMapper;
import com.example.project.projectspringcloud.dao.video.VideoMapper;
import com.example.project.projectspringcloud.entity.Page;
import com.example.project.projectspringcloud.entity.sys.SysConfig;
import com.example.project.projectspringcloud.entity.user.User;
import com.example.project.projectspringcloud.entity.video.Video;
import com.example.project.projectspringcloud.service.BaseService;
import com.example.project.projectspringcloud.service.user.UserService;
import com.example.project.projectspringcloud.service.video.VideoService;
import com.example.project.projectspringcloud.utils.RedisUtil;
import com.example.project.projectspringcloud.utils.TencentVideoUtil;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Service
@Transactional(rollbackFor = Exception.class)
public class VideoServiceImpl extends BaseService<Video, VideoMapper> implements VideoService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Video get(Video video) {
        Video exist = null;
        if (redisUtil.hasKey(Constants.VIDEO_CACHE_PREFIX + video.getId())) {
            String videoJson = (String) redisUtil.get(Constants.VIDEO_CACHE_PREFIX + video.getId());
            exist = new Gson().fromJson(videoJson, Video.class);
        } else {
            exist = super.mapper.selectOne(video);
        }

        if (exist != null) {
            if (exist.getPhotoGrapher() != null) {
                exist.setPhotoGrapherUser(userMapper.selectOne(new User(exist.getPhotoGrapher())));
            }

            if (exist.getScriptWriter() != null) {
                exist.setScriptWriterUser(userMapper.selectOne(new User(exist.getScriptWriter())));
            }
        }

        return exist;
    }

    @Override
    public List<Video> list(Page page, Video video) {
        // 获取系统配置
        List<SysConfig> sysConfigs = sysConfigMapper.selectAll(new SysConfig("tencentcloud"));
        // 分页
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        // 获取视频列表
        List<Video> videos = super.mapper.selectAll(video);
        // 加载视频腾讯点播接口
        videos.forEach(t -> {
            try {
                TencentVideoUtil.getTCPlayParam(t, false, sysConfigs, redisUtil, false);
            } catch (Exception e) {
                logger.error(String.format("Get tencent production info failed! Video id : %s.", t.getId()), e);
            }
        });
        return videos;
    }

    @Override
    public boolean delete(Integer[] ids) {
        for (Integer id : ids) {
            redisUtil.del(Constants.VIDEO_CACHE_PREFIX + id);
        }
        return super.mapper.deleteByArrayPrimaryKey(ids) > 0;
    }

    @Override
    public boolean save(Video video) {
        if (super.save(video)) {
            try {
                refresh(new Integer[]{video.getId()});
            } catch (Exception e) {
                logger.error("Video save refresh failed! Video ID: {}", video.getId());
                e.printStackTrace();
            }
        }
        return true;
    }

    @Override
    public boolean changeshow(Video video) throws OperationException {
        String filtrate = video.getFiltrate();
        video = super.mapper.selectOne(video);
        if (video != null) {
            video.setFiltrate(filtrate);
            if (super.mapper.updateByPrimaryKeySelective(video) < 1) {
                return false;
            }
        } else {
            return false;
        }
        return true;
    }

    @Override
    public int count(Integer videoId) throws OperationException {
        // 获取视频原信息
        Video video = this.get(new Video(videoId));
        Optional<Video> videoOptional = Optional.ofNullable(video);
        if (videoOptional.isPresent()) {
            video.setCount(video.getCount() + 1);
            // 同时更新缓存中视频信息
            redisUtil.set(Constants.VIDEO_CACHE_PREFIX + video.getId(), new Gson().toJson(video), 82800);
            super.mapper.updateCount(video.getId(), video.getCount());
            return video.getCount();
        } else {
            throw new OperationException(Constants.Message.VIDEO_INFO_DOES_NOT_EXIST);
        }
    }

    @Override
    public List<Video> list(Set<Integer> ids, Integer type) {
        return super.mapper.selectAllByIdsAndType(ids, type);
    }

    @Override
    public void refresh(Integer[] idarr) throws Exception {
        // 获取系统配置
        List<SysConfig> sysConfigs = sysConfigMapper.selectAll(new SysConfig("tencentcloud"));
        for (Integer id : idarr) {
            Video video = super.mapper.selectOne(new Video(id));
            TencentVideoUtil.getTCPlayParam(video, false, sysConfigs, redisUtil, true);
        }
    }
}
